# -*- coding: utf-8 -*-
import logging
import os
from crawler.utils.Singleton import Singleton
from setting import project_path, administrator

log_path = os.path.join(project_path, 'log')
config_file = os.path.join(log_path, 'log')


@Singleton
class Log:

    def __init__(self, level='DEBUG'):
        # 日志器对象
        self.log = logging.getLogger(administrator)
        self.log.setLevel(level)
        if not os.path.exists(log_path):
            os.makedirs(log_path)

    def console_handle(self, level='DEBUG'):
        """控制台处理器"""
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)
        # 处理器添加格式
        console_handler.setFormatter(self.get_formatter()[0])
        return console_handler

    def file_handle(self, level='DEBUG'):
        """文件处理器"""
        file_handler = logging.FileHandler(config_file, mode='a', encoding='utf-8')
        file_handler.setLevel(level)
        # 处理器添加格式
        file_handler.setFormatter(self.get_formatter()[1])
        return file_handler

    def get_formatter(self):
        """格式器"""
        console_fmt = logging.Formatter(
            fmt='[%(name)s] '
                '[%(levelname)s] '
                '[%(asctime)s] '
            # '[%(module)s] '
            # '[%(funcName)s] '
            # '[%(thread)d] '
            # '[%(threadName)s] '
            # '[%(process)d] '
                '[%(message)s]')
        file_fmt = logging.Formatter(
            fmt='[%(name)s] '
                '[%(levelname)s] '
                '[%(asctime)s] '
            # '[%(module)s] '
            # '[%(funcName)s] '
            # '[%(thread)d] '
            # '[%(threadName)s] '
            # '[%(process)d] '
                '[%(message)s]')
        return console_fmt, file_fmt

    def get_log(self):
        # 日志添加控制台处理器
        self.log.addHandler(self.console_handle())
        # 日志器添加文件处理器
        self.log.addHandler((self.file_handle()))
        # 返回日志实例对象
        return self.log


log = Log()
logger = log.get_log()
